const express = require('express')
const router = express.Router()

// 自定义库
const db = require('../config/database.js')
const code = require('../config/code.js')
const Tag = require('../model/tag.js')

router.get('/get', (req, res, next) => {
  (async () => {
    const [errFind, resFind] = await db.query(Tag.findAllByUserId, [req.auth.id])
    if (errFind) {
      res.json({code: code.dbErr, msg: '获取失败'})
      return
    }
    res.json({
      code: code.ok,
      msg: '获取成功',
      data: resFind
    })
  })()
})

router.get('/delete', (req, res, next) => {
  (async () => {
    const { id } = req.query
    if (!id) {
      return res.json({code: code.paraErr, msg: '缺少参数'})
    }
    const [errDel, resDel] = await db.query(Tag.delById, [id, req.auth.id])
    if (errDel) {
      return res.json({code: code.dbErr, msg: '删除失败'})
    }
    if (resDel.affectedRows === 0) {
      return res.json({code: code.dbErr, msg: '删除失败'})
    }
    return res.json({
      code: code.ok,
      msg: '删除成功',
      data: {
        id: id
      }
    })
  })()
})

router.get('/add', (req, res, next) => {
  (async () => {
    const { name } = req.query
    if (!name) {
      res.json({code: code.paraErr, msg: '请输入标签名称'})
      return
    }
    const [errFind, resFind] = await db.query(Tag.findIdByName, [name])
    if (errFind) {
      res.json({code: code.dbErr, msg: '添加失败'})
      return
    }
    if (resFind.length !== 0) {
      res.json({code: code.paraErr, msg: '添加失败，已经有重复的标签'})
      return      
    }
    const [errAdd, results] = await db.query(Tag.addFile, [req.auth.id, name])
    if (errAdd) {
      res.json({code: code.dbErr, msg: '添加失败'})
      return
    }
    if (results.affectedRows === 0) {
      res.json({code: code.dbErr, msg: '添加失败'})
      return      
    }
    res.json({
      code: code.ok,
      msg: '添加成功',
      data: {
        id: results.insertId,
        name: name
      }
    })
  })()
})


module.exports = router
